# This code was writen BY Huang Studio

import sys
import os
# pip install requests
import requests
import random
from time import *
import datetime

os.environ['NTCHAT_LOG'] = "ERROR"
# pip install ntchat
import ntchat

# 格式化输出的时间
ISOTIMEFORMAT = '%Y-%m-%d %H:%M:%S'

# chinese ：

nowTime = datetime.datetime.now().strftime(ISOTIMEFORMAT)
print(f"{nowTime}   启动程序")

# 设置堆积种子
random.seed()

# settings
# 请完善以下的设置 否则无法运行
# ======================================
# 注:以下微信信息均填写wxid,不是微信号,是wxid,不是微信号,是wxid!!!
# 微信黑名单 里面的人就算出发了关键词也不会被回复
sb_wxid = []
# 大号的wxid,程序正常启动时会给填写的大号发送一条消息 没有可不填
large_wxid = ""
# 微信名
wechat_name = ""
# ChatGPT的API
api_key = ""
# ======================================
nowTime = datetime.datetime.now().strftime(ISOTIMEFORMAT)
print(f"{nowTime}   获取设置成功")


# send msg
def send_msg(wxid, msg):
    # 发送消息函数
    wechat.send_text(to_wxid=str(wxid), content=str(msg))
    nowTime = datetime.datetime.now().strftime(ISOTIMEFORMAT)
    print(f"{nowTime}   发送了一则消息\"{msg}\" 至 \"{wxid}\"")

        
# start ChatGPT
prompt = ""
headers = {"Authorization": f"Bearer {api_key}"}
api_url = "https://api.openai.com/v1/completions"
nowTime = datetime.datetime.now().strftime(ISOTIMEFORMAT)
print(f"{nowTime}   ChatGPT初始化成功")


def ChatGPT_result(que):
    nowTime = datetime.datetime.now().strftime(ISOTIMEFORMAT)
    print(f"{nowTime}   ChatGPT收到请求\"{que}\"")
    prompt = str(que)
    data = {'prompt': prompt,
            # 使用的模型
            "model": "text-davinci-003",
            # 最大返回值 使用随机数设置吧
            'max_tokens': random.randint(1000, 2000),
            'temperature': 1,
            }
    response = requests.post(api_url, json=data, headers=headers)
    resp = response.json()
    chat_gpt_result = str(resp["choices"][0]["text"].strip())
    nowTime = datetime.datetime.now().strftime(ISOTIMEFORMAT)
    print(f"{nowTime}   ChatGPT返回了一则消息\"{chat_gpt_result}\"")
    return chat_gpt_result

# 黑名单去重
sb_wxid = list(set(sb_wxid))

# connect wechat
wechat = ntchat.WeChat()
wechat.open(smart=True)
nowTime = datetime.datetime.now().strftime(ISOTIMEFORMAT)
print(f"{nowTime}   接管微信 等待登陆")
# 打开微信 等待登陆
wechat.wait_login()
nowTime = datetime.datetime.now().strftime(ISOTIMEFORMAT)
print(f"{nowTime}   接管微信成功")
if len(large_wxid) != 0:
    # 启动成功后给大号发一则消息
    wechat.send_text(to_wxid=large_wxid, content=f"{nowTime} ChatGPT微信已启动")

# keep wechat running
# os.system("C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python38-32\\python.exe C:\\Users\\Administrator\\Desktop\\WechatRobot\\src\\check_wechat_run.py")

# get rooms and contacts list
# rooms = wechat.get_rooms()
# contacts = wechat.get_contacts()
# nowTime = datetime.datetime.now().strftime(ISOTIMEFORMAT)
# print(f"{nowTime}   获取联系人及群列表成功")

# check send (people)
# 确认收到的消息是否出发了关键词并且符合要求
def check_send_people(from_wxid, get_msg):
    if from_wxid not in sb_wxid and from_wxid not in myself_wxit:
        if get_msg.find("chatgpt：") != -1 or get_msg.find("chatgpt:") != -1:
            nowTime = datetime.datetime.now().strftime(ISOTIMEFORMAT)
            print(f"{nowTime}   触发了一条消息\"{get_msg}\"")
            return True
        else:
            nowTime = datetime.datetime.now().strftime(ISOTIMEFORMAT)
            print(f"{nowTime}   消息未触发：不包含关键字")
            return False
    else:
        nowTime = datetime.datetime.now().strftime(ISOTIMEFORMAT)
        print(f"{nowTime}   消息未触发：来自自己｜处于黑名单")
        return False


# get msg
@wechat.msg_register(ntchat.MT_RECV_TEXT_MSG)
def on_recv_text_msg(wechat_instance: ntchat.WeChat, message):
    # 收到一条新消息
    # 读取消息内容 发送着
    data = message["data"]
    from_wxid = data["from_wxid"]
    self_wxid = wechat_instance.get_login_info()["wxid"]
    room_wxid = data["room_wxid"]
    get_msg = data["msg"]

    if from_wxid != self_wxid:
        nowTime = datetime.datetime.now().strftime(ISOTIMEFORMAT)
        print(f"{nowTime}   收到一条消息：\"{get_msg}\" 来自 \"{from_wxid}\"")
        result_send = check_send_people(from_wxid=from_wxid, get_msg=get_msg)
        if result_send:
            nowTime = datetime.datetime.now().strftime(ISOTIMEFORMAT)
            get_msg = get_msg.replace("chatgpt：","")
            get_msg = get_msg.replace("chatgpt:","")
            print(f"{nowTime}   发送消息至chatgpt")
            result_chat = ChatGPT_result(get_msg)
            sleep(random.randint(2, 6))
            if room_wxid != "":
                # at_list = []
                # at_list.append(from_wxid)
                send_msg(room_wxid, result_chat)
            else:
                # at_list = []
                send_msg(from_wxid, result_chat)
            



try:
    while True:
        pass
except KeyboardInterrupt:
    ntchat.exit_()
    sys.exit()
